<?php

namespace app\common\model\cms;

use app\common\model\BaseModel;
use helper\DbHandler;

class FieldModel extends BaseModel
{

  protected $table = 'cms_field';

  /**
   * 添加字段
   * @param $data
   * @return mixed
   * @throws \Exception
   */
  public function add($data)
  {
    $db            = $this->db();
    $fullTableName = "cms_detail_{$data['table_name']}";
    if (DbHandler::checkField($fullTableName, $data['field_name']) === true) {
      abort(500, "{$data['table_name']}表中该字段已存在");
    }
    if ($this->where('table_name', $data['table_name'])->where('field_name', $data['field_name'])->find()) {
      abort(500, '已存在对应字段配置');
    }
    //取出目前最后一个字段
    $afterField = $this->where('table_name', $data['table_name'])->order('show_order desc')->value('field_name');
    $info       = null;
    $db->startTrans();
    try {
      //添加对应字段
      $fieldSql = "";
      switch ($data['field_type']) {
        case 'char':
        case 'varchar':
          $fieldSql = "ALTER TABLE {$fullTableName} ADD `{$data['field_name']}` {$data['field_type']}({$data['field_length']}) DEFAULT '' COMMENT '{$data['label_name']}' AFTER `{$afterField}`";
          break;
        case 'tinyint':
        case 'int':
        case 'float':
        case 'double':
        case 'decimal':
          $fieldSql = "ALTER TABLE `{$fullTableName}` ADD `{$data['field_name']}` {$data['field_type']}({$data['field_length']}) DEFAULT '0' COMMENT '{$data['label_name']}' AFTER `{$afterField}`";
          break;
        case 'text':
        case 'mediumtext':
        case 'longtext':
          $fieldSql = "ALTER TABLE `{$fullTableName}` ADD `{$data['field_name']}` {$data['field_type']} COMMENT '{$data['label_name']}' AFTER `{$afterField}`";
          break;
        case 'date':
        case 'datetime':
          $fieldSql = "ALTER TABLE `{$fullTableName}` ADD `{$data['field_name']}` {$data['field_type']} DEFAULT NULL COMMENT '{$data['label_name']}' AFTER `{$afterField}`";
          break;
      }
      if (empty($fieldSql)) abort(500, '字段类型不正确！');
      $db->execute($fieldSql);
      //添加字段配置信息
      $info = self::create($data);
      //刷新缓存
      $tableModel = new TableModel();
      $tableModel->getInfo($data['table_name'],true);
      $db->commit();
    } catch (\Exception $e) {
      $db->rollback();
      abort(500, $e->getMessage());
    }
    return $info;
  }

  /**
   * 编辑字段
   * @param $data
   * @return FieldModel
   * @throws \Exception
   */
  public function edit($data)
  {
    if (isset($data['table_name'])) unset($data['table_name']);
    if (isset($data['field_name'])) unset($data['field_name']);
    if (isset($data['field_type'])) unset($data['field_type']);
    if (isset($data['field_length'])) unset($data['field_length']);
    $data['obj_options'] = html_out($data['obj_options']);
    $data['obj_status']  = isset($data['obj_status']) ? 1 : 0;
    $info = self::update($data);
    //刷新缓存
    $tableName = $this->where('id',$data['id'])->value('table_name');
    $tableModel = new TableModel();
    $tableModel->getInfo($tableName,true);
    return $info;
  }

  /**
   * 删除字段
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    $db        = $this->db();
    $info      = $this->where('id', $id)->find();
    $tableName = "cms_detail_{$info['table_name']}";
    //不允许删除字段
    if (in_array($info['field_name'], ['title', 'class_id', 'uid', 'create_time', 'update_time'])) {
      abort(500,'该字段不允许删除！');
    }
    //删除物理字段
    $fields = array_keys($db->getFields($tableName));
    if (in_array($info['field_name'], $fields)) {
      $sql = "ALTER TABLE {$tableName} DROP " . $info['field_name'];
      $db->execute($sql);
    }
    //删除字段记录
    $this->where('id', $id)->delete();
    //刷新缓存
    $tableModel = new TableModel();
    $tableModel->getInfo($tableName,true);
    return true;
  }

  /**
   * 获取mysql字段类型
   * @return array
   */
  public function getFieldTypes()
  {
    return [
        ['key' => 'tinyint', 'name' => '小整数值[tinyint]'],
        ['key' => 'int', 'name' => '大整数值[int]'],
        ['key' => 'float', 'name' => '单精度浮点数值[float]'],
        ['key' => 'double', 'name' => '双精度浮点数值[double]'],
        ['key' => 'decimal', 'name' => '货币数值[decimal]'],
        ['key' => 'char', 'name' => '定长字符串[char]'],
        ['key' => 'varchar', 'name' => '变长字符串[varchar]'],
        ['key' => 'text', 'name' => '长文本字符串[text]'],
        ['key' => 'mediumtext', 'name' => '中等长度文本数据[mediumtext]'],
        ['key' => 'longtext', 'name' => '极大文本数据[longtext]'],
        ['key' => 'date', 'name' => '日期值[date]'],
        ['key' => 'datetime', 'name' => '混合日期和时间值[datetime]'],
    ];
  }

  /**
   * 控件类型
   * @return array
   */
  public function getObjTypes()
  {
    return [
        ['key' => '_text', 'name' => '文本框'],
        ['key' => '_password', 'name' => '密码框'],
        ['key' => '_hidden', 'name' => '隐藏框'],
        ['key' => '_laydate', 'name' => '日期框'],
        ['key' => '_number', 'name' => '数字框'],
        ['key' => '_textarea', 'name' => '多行文本框'],
        ['key' => '_switch', 'name' => 'switch框'],
        ['key' => '_tags', 'name' => 'tags框'],
        ['key' => '_ckeditor', 'name' => '富文本框'],
        ['key' => '_ace', 'name' => '代码编辑框'],
        ['key' => '_area', 'name' => '省市区级联框'],
        ['key' => '_select', 'name' => '下拉框'],
        ['key' => '_checkbox', 'name' => '多选框'],
        ['key' => '_radio', 'name' => '单选框'],
        ['key' => '_selectPage', 'name' => 'selectPage框'],
        ['key' => '_uploadImage', 'name' => '单图上传'],
        ['key' => '_uploadImages', 'name' => '多图上传'],
        ['key' => '_uploadFile', 'name' => '单附件上传'],
        ['key' => '_uploadFiles', 'name' => '多附件上传']
    ];
  }

}